// pages/jimengvoice/jimengvoice.js
var app = getApp()
var util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    j: 1,//帧动画初始图片
    isSpeaking: false,//是否正在说话
    isSpeaking2: false,//是否正在说话
    leftTime: 60,
    isThereVoice: false,
    voiceFilePath: "",
    recordFilePath: "",
    voiceCreateTime: "",
    voiceLength: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  //手指按下
  touchdown: function () {
    var that = this;
    console.log("手指按下了...")
    console.log("new date : " + new Date)

    //检查是否已经满3条
    wx.request({
      url: 'https://api.jiemengshi.com/wechat/dream/voice/count',
      header: {
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 0) {
          //未达次数上限
          if (res.data.data <= 2) {

            //开始录音
            var _this = that;
            speaking.call(that);
            myTimer.call(that);
            that.setData({
              isSpeaking: true,
              isSpeaking2: true
            })
            wx.startRecord({
              success: function (res) {
                console.log(res)
                //临时路径,下次进入小程序时无法正常使用
                var tempFilePath = res.tempFilePath
                var createTime = util.formatTime(new Date());
                console.log("tempFilePath: " + tempFilePath)
                _this.setData({
                  recordFilePath: tempFilePath,
                  isThereVoice: true,
                  leftTime: 60,
                  voiceFilePath: tempFilePath,
                  voiceCreateTime: createTime
                })
                wx.showToast({
                  title: '恭喜!录音成功',
                  icon: 'success',
                  duration: 1000
                })
                //持久保存
                // wx.saveFile({
                //   tempFilePath: tempFilePath,
                //   success: function (res) {
                //     //持久路径
                //     //本地文件存储的大小限制为 100M
                //     console.log(res)
                //     var savedFilePath = res.savedFilePath
                //     console.log("savedFilePath: " + savedFilePath)
                //     var createTime = util.formatTime(new Date());
                //     _this.setData({
                //       voiceCreateTime: createTime
                //     })
                //   }
                // })
                // //获取录音音频列表
                // wx.getSavedFileList({
                //   success: function (res) {
                //     var index = res.fileList.length - 1
                //     var filePath = res.fileList[index].filePath
                //     var size = (res.fileList[index].size / 1024).toFixed(2);

                //     _this.setData({
                //       isThereVoice: true,
                //       leftTime: 60,
                //       voiceFilePath: filePath,
                //       voiceSize: size
                //     })
                //   }
                // })
              },
              fail: function (res) {
                //录音失败
                wx.showModal({
                  title: '提示',
                  content: '录音的姿势不对!',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      return
                    }
                  }
                })
              }
            })

          }
          else {
            wx.showModal({
              title: '已达上限',
              content: "每日上限3条，你已达此上限，请明天再次尝试",
              showCancel: false
            })
          }
        }
      }
    })
  },
  //手指抬起
  touchup: function () {
    console.log("手指抬起了...")
    console.log(this.data.leftTime)
    var timeLength = 60 - this.data.leftTime
    this.setData({
      isSpeaking: false,
      isSpeaking2:false,
      leftTime: 60,
      voiceLength: timeLength
    })
    clearInterval(this.timer)
    clearInterval(this.timer2)
    wx.stopRecord()
  },

  //点击播放录音
  gotoPlay: function (e) {
    var filePath = e.currentTarget.dataset.key;
    //点击开始播放
    wx.showToast({
      title: '开始播放',
      icon: 'success',
      duration: 1000
    })
    wx.playVoice({
      filePath: filePath,
      success: function () {
        wx.showToast({
          title: '播放结束',
          icon: 'success',
          duration: 1000
        })
      },
      fail: function(){
        wx.showToast({
          title: '播放失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },

  //上传
  uploadVoice: function(e){
    var formId = e.detail.formId;
    console.log('form发生了submit事件，推送码为：', formId)

    var filePath = this.data.recordFilePath;
    var voiceCreateTime = this.data.voiceCreateTime;
    var that = this;
    var uptoken = "";
    //获取uptoken
    wx.request({
      url: 'https://api.jiemengshi.com/attachment/qiniu/voice/uptoken',
      header: {
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        uptoken = res.data.data
        console.log(uptoken)
        //上传
        qiniuUploader.upload(filePath, (res) => {
          console.log(res)
          console.log(res.data)
          var result = JSON.parse(res.data)
          console.log(result.code)
          console.log(result.code == 0)
          if(result.code == 0){
            //存储梦境
            wx.request({
              url: 'https://api.jiemengshi.com/wechat/dream/record/add',
              data: {
                title: voiceCreateTime,
                content: voiceCreateTime,
                voiceRecordId: result.data.attachmentId,
                formId: formId
              },
              header: {
                'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
              },
              success: function (res) {
                console.log(res)
                console.log(res.data.code)
                if (res.data.code == 0) {
                  wx.showToast({
                    title: '语音记梦成功',
                  })
                  wx.navigateBack({
                    delta: 1 //返回的页面数
                  })
                }
                else {
                  wx.showModal({
                    title: '语音记梦失败',
                    content: "请稍候再次尝试",
                    showCancel: false
                  })
                }
              },
              faile: function(e){
                console.log(e)
              }
            })
          }
        }, 
        (error) => {
          console.log('error: ' + error);
        }, 
        {
            region: 'NCN',
            domain: 'voice.jiemengshi.com', 
            key: voiceCreateTime + ".silk", 
            uptoken: uptoken
        });      
      }
    }) 
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

//计时
function myTimer(){
  var _this = this;
  this.timer2 = setInterval(function(){
    var originTime = _this.data.leftTime
    if (originTime > 1) {
      _this.setData({
        leftTime: originTime - 1
      })
    }
    else {
      console.log("已达60秒")
      _this.setData({
        isSpeaking: false,
        isSpeaking2:false
      })
      clearInterval(_this.timer)
      clearInterval(_this.timer2)
      wx.stopRecord()
      _this.setData({
        leftTime: 60
      })
    }
  },1000)
}